package mamikeji.liaowa.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import mamikeji.liaowa.R;
import mamikeji.liaowa.application.MyApplication;
import mamikeji.liaowa.http_api.ForHttp;
import mamikeji.liaowa.http_api.HttpApi;
import mamikeji.liaowa.http_api.HttpKey;
import mamikeji.liaowa.utils.ForContents;
import mamikeji.liaowa.utils.ForLog;
import mamikeji.liaowa.utils.ForPreference;
import mamikeji.liaowa.utils.ForToast;
import mamikeji.liaowa.utils.MaxTextLength;
import mamikeji.liaowa.utils.SystemUtils;
import mamikeji.liaowa.utils.XingZuo;

public class WaMsgActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "WaMsgActivity";
    @BindView(R.id.editText_wamsg_name)
    public EditText editText_wamsg_name;
    @BindView(R.id.textView_wamsg_birthday_title)
    public TextView textView_wamsg_birthday_title;
    @BindView(R.id.textView_msg_birthday)
    public TextView textView_msg_birthday;
    @BindView(R.id.linearLayout_wamsg_sex_visibility)
    public LinearLayout linearLayout_wamsg_sex_visibility;
    @BindView(R.id.linearLayout_wamsg_nan)
    public LinearLayout linearLayout_wamsg_nan;
    @BindView(R.id.linearLayout_wamsg_nv)
    public LinearLayout linearLayout_wamsg_nv;
    @BindView(R.id.linearLayout_msg_birthday)
    public LinearLayout linearLayout_msg_birthday;
    @BindView(R.id.relativeLayout_wamsg_query)
    public RelativeLayout relativeLayout_wamsg_query;
    @BindView(R.id.imageView_nan)
    public ImageView imageView_nan;
    @BindView(R.id.imageView_nv)
    public ImageView imageView_nv;

    private Boolean boolean_static;
    private String wa_sex, wa_nickname, wa_birthday;

    //时间选择器
    TimePickerView pvTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wamsg);
        getBase();
        ButterKnife.bind(this);
        setTitleLeftBtn();
        setTitleName(R.string.wamsg_name);
        Intent mIntent = getIntent();
        boolean_static = mIntent.getBooleanExtra("user_staic", false);
        init();
        initData();
    }

    /**
     * 加载布局控件
     */
    private void init() {
        if (boolean_static) {
            //已出生
            time_data_YCS();
        } else {
            //未出生
            time_data_YCQ();
        }

        InputFilter[] filters = new InputFilter[]{new MaxTextLength(16)};
        editText_wamsg_name.setFilters(filters);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        if (boolean_static) {
            wa_sex = "1";
            imageView_nan.setImageResource(R.drawable.icon_nan_h);
            imageView_nv.setImageResource(R.drawable.icon_nv_n);
            textView_wamsg_birthday_title.setText(R.string.wamsg_birthday);
            linearLayout_wamsg_sex_visibility.setVisibility(View.VISIBLE);
        } else {
            textView_wamsg_birthday_title.setText(R.string.wamsg_birthday_null);
            linearLayout_wamsg_sex_visibility.setVisibility(View.GONE);
        }
    }

    @OnClick({R.id.linearLayout_wamsg_nan,
            R.id.linearLayout_wamsg_nv,
            R.id.relativeLayout_wamsg_query,
            R.id.linearLayout_msg_birthday})
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.linearLayout_msg_birthday:
                isKeyboardShownToHideKeyboard();
                pvTime.show();
                break;
            case R.id.linearLayout_wamsg_nan:
                wa_sex = "1";
                imageView_nan.setImageResource(R.drawable.icon_nan_h);
                imageView_nv.setImageResource(R.drawable.icon_nv_n);
                break;
            case R.id.linearLayout_wamsg_nv:
                wa_sex = "0";
                imageView_nan.setImageResource(R.drawable.icon_nan_n);
                imageView_nv.setImageResource(R.drawable.icon_nv_h);
                break;
            case R.id.relativeLayout_wamsg_query:
                if (TextUtils.isEmpty(editText_wamsg_name.getText().toString())) {
                    ForToast.showToast(R.string.wamsg_error_name);
                    return;
                } else if (boolean_static) {
                    if (TextUtils.isEmpty(wa_birthday)) {
                        ForToast.showToast(R.string.wamsg_error_birthday);
                        return;
                    }
                    if (TextUtils.isEmpty(textView_msg_birthday.getText().toString())) {
                        ForToast.showToast(R.string.wamsg_error_birthday);
                        return;
                    }
                } else if (boolean_static) {
                    if (TextUtils.isEmpty(wa_sex)) {
                        ForToast.showToast(R.string.wamsg_error_sex);
                        return;
                    }
                }
                wa_nickname = editText_wamsg_name.getText().toString();
                getAddBoby();
                break;
        }
    }

    /**
     * 添加个娃
     */
    public void getAddBoby() {
        showLoading();
        //参数集合
        Map<String, String> formMap = new HashMap<String, String>();
        formMap.put(HttpKey.ADD_USERCODE, ForPreference.getString(ForContents.USER_CODE));
        formMap.put(HttpKey.ADD_STATUS, boolean_static ? "2" : "1");
        formMap.put(HttpKey.ADD_BIRTHTIME, wa_birthday);
        formMap.put(HttpKey.ADD_NICKNAME, wa_nickname);
        formMap.put(HttpKey.ADD_CONSTELLATION, getAstro(month_n, day_n));

        formMap.put(HttpKey.ADD_WEIGHT, "0");
        formMap.put(HttpKey.ADD_HEIGHT, "0");

        formMap.put(HttpKey.ADD_DESCRIBE, "");
        formMap.put(HttpKey.ADD_CREATETIME, "2017-06-09");

        if (boolean_static) {
            formMap.put(HttpKey.ADD_SEX, wa_sex);
        }

        ForHttp.setMsg(HttpApi.ROOT_PATH + HttpApi.Add_BODY, formMap, new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                ForLog.i(TAG, e.getMessage());
                ForToast.showToast(R.string.intent_error);
                hideLoading();
            }

            @Override
            public void onResponse(String response) {
                Log.e(TAG, response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString(HttpKey.STATUS);
                    if ("200".equals(status)) {
                        startActivity(new Intent(WaMsgActivity.this, MainActivity.class));
                        MyApplication.getInstance().closeActivity(new AddWaActivity());
                        finish();
                    }
                    hideLoading();
                    ForToast.showToast(jsonObject.getString(HttpKey.MESSAGE));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 预产期
     */
    public void time_data_YCQ() {
        int years = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
        int months = Integer.parseInt(new SimpleDateFormat("MM").format(new Date()));
        int days = Integer.parseInt(new SimpleDateFormat("dd").format(new Date()));

        int endY = years + 1;

        Calendar startDate = Calendar.getInstance();
        startDate.set(years, months - 1, days);
        Calendar endDate = Calendar.getInstance();
        endDate.set(endY, months - 1, days);

        boolean[] booleen = new boolean[]{true, true, true, false, false, false};
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                month_n = Integer.parseInt(getTime(date, "MM"));
                day_n = Integer.parseInt(getTime(date, "dd"));
                wa_birthday = getTime(date, "yyyy-MM-dd");
                textView_msg_birthday.setText(wa_birthday);
            }
        })
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setType(booleen)//默认全部显示
                .setLabel("", "", "", "", "", "")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
    }

    /**
     * 已出生
     */
    public void time_data_YCS() {
        int endY = 0;
        int years = Integer.parseInt(new SimpleDateFormat("yyyy").format(new Date()));
        int months = Integer.parseInt(new SimpleDateFormat("MM").format(new Date()));
        int days = Integer.parseInt(new SimpleDateFormat("dd").format(new Date()));

        endY = years - 6;
        months = months - 1;

        Calendar startDate = Calendar.getInstance();
        startDate.set(endY, months, days);
        Calendar endDate = Calendar.getInstance();
        endDate.set(years, months, days);

        boolean[] booleen = new boolean[]{true, true, true, false, false, false};
        pvTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                month_n = Integer.parseInt(getTime(date, "MM"));
                day_n = Integer.parseInt(getTime(date, "dd"));
                wa_birthday = getTime(date, "yyyy-MM-dd");
                textView_msg_birthday.setText(wa_birthday);
            }
        })
                .setRangDate(startDate, endDate)//起始终止年月日设定
                .setType(booleen)//默认全部显示
                .setLabel("", "", "", "", "", "")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
        pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
    }

    public static String getTime(Date date, String timeType) {
        SimpleDateFormat format = new SimpleDateFormat(timeType);
        return format.format(date);
    }

    private int month_n;
    private int day_n;

    //获取星座
    private String getAstro(int month, int day) {
//        String[] astro = new String[]{"摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座",
//                "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"};
//        int[] arr = new int[]{20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22};// 两个星座分割日
//        int index = month;
//        // 所查询日期在分割日之前，索引-1，否则不变
//        if (day < arr[month - 1]) {
//            index = index - 1;
//        }
//        // 返回索引指向的星座string
//        return astro[index];

        //优化星座越界
        return XingZuo.getXingZuoName(month, day);
    }

    /**
     * 判断软键盘是否弹起如弹起则隐藏
     */
    private void isKeyboardShownToHideKeyboard() {
        if (SystemUtils.isKeyboardShown(editText_wamsg_name.getRootView())) {
            SystemUtils.hideKeyboard(this, editText_wamsg_name.getApplicationWindowToken());
        }
    }

}
